<?php
namespace common\components;

use Yii;
use yii\web\Controller;
use yii\web\HttpException;
 /**
  * 集成常用公用方法,提供给给有Controller使用
  * get,post,setCookie,getCooke,removeCookie,
  * return : json
  */
class BaseWebController extends Controller
{
	#关闭csrf
	public $enableCsrfValidation = false; 

	// 获取http的get参数
	public function get($key, $default = "") {
		return \Yii::$app->request->get($key, $default);
	}

	// 获取http的post参数
	public function post($key, $default = "") 
	{
		return \Yii::$app->request->post($key, $default);
	}

	// 设置cookie值
	protected function setCookie($name,$value,$expire = 0)
	{
		$cookies = \Yii::$app->response->cookies;
		$cookies->add( new \yii\web\Cookie([
			'name' => $name,
			'value' => $value,
			'expire' => $expire
		]));
	}

	// 获取cookie值
	protected  function getCookie($name,$default_val='')
	{
		$cookies = \Yii::$app->request->cookies;
		return $cookies->getValue($name, $default_val);
	}

	// 删除cookie值
	protected function removeCookie($name)
	{
		$cookies = \Yii::$app->response->cookies;
		$cookies->remove($name);
	}

	// protected function renderJSON($data=[], $msg ="ok", $code = 200)
	// {
	// 	header('Content-type: application/json');
	// 	echo json_encode([
	// 		"code" => $code,
	// 		"msg"   =>  $msg,
	// 		"data"  =>  $data,
	// 		"req_id" =>  uniqid()
	// 	]);

	// 	return \Yii::$app->end();
	// }

	protected function renderJSON($data=[], $msg ="ok", $code = 200)
	{
		header('Content-type: application/json');
		$jsonResult = json_encode([
			"code" => $code,
			"msg" => $msg,
			"data" => $data,
			"req_id" => uniqid()
		]);
		return $jsonResult;
	}

	//统一js提醒
	protected  function renderJS($msg,$url = "/")
	{
		return $this->renderPartial("@app/views/common/js", ['msg' => $msg, 'location' => $url]);
	}
}


